package com.yicong.ants.utils;

import android.content.Context;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestFutureTarget;
import com.cchao.simplelib.LibCore;
import com.cchao.simplelib.core.GlideOptions;

import java.io.File;
import java.lang.reflect.Field;

/**
 * Description :
 *
 * @author ZhJiao
 * @date 2021/9/1
 */
public class CacheUtils {


    public static File getCache(String url) {
        Context context = LibCore.getContext();
        File cacheFile = null;
        RequestFutureTarget<File> futureTarget = (RequestFutureTarget<File>) Glide.with(context).downloadOnly().load(url).apply(new GlideOptions().onlyRetrieveFromCache(true)).submit();
        Class<?> class1 = futureTarget.getClass();
        Field field = null;
        try {
            //等待Glide给resource对象赋值
            synchronized (futureTarget) {
                futureTarget.wait();
            }
            field = class1.getDeclaredField("resource");
            field.setAccessible(true);//开放权限
            cacheFile = (File) field.get(futureTarget);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return cacheFile;
    }

    public static boolean isCache(String url) {
        return getCache(url) != null;
    }


}
